<?php
namespace app\index\controller;

use app\index\model\Article as ArticleModel;
use app\index\model\SystemConfig;
use app\index\model\Label;

class Article
{
    public function index($query, $page=1, $pageSize=10, $sort='create_time', $order='desc'){
        $where = [['status', '=', 1]];
        $whereAssoc = [];
        //判断
        $queryArr = [];
        $query = array_filter(explode(' ', $query));
        foreach ($query as $item) {
            list($k, $v) = explode(':', $item);
            $queryArr[$k] = $v;
        }
        // 关键字过滤
        if (array_key_exists('keyword', $queryArr)){
            $where[] = ['title', 'like', "%{$queryArr['keyword']}%"];
        }
        // 文章分类过滤
        if (array_key_exists('category', $queryArr)){
            $whereAssoc['category'] = ['name', '=', $queryArr['category']];
        }
        // 文章标签过滤
        if (array_key_exists('label', $queryArr)){
            //多对多不支持haswhere方法
            $info = Label::where(['name'=>$queryArr['label']])->find();
            if (!$info->article->toArray()){
                return json([]);
            }
            $where[] = ['id', 'in', array_column($info->article->toArray(), 'id')];
        }
        //获取列表
        $article = new ArticleModel();
        $list = $article->getDetail($where, $whereAssoc, $page, $pageSize);
        if ($list->isEmpty()){
            return json([]);
        }
        $list->load('label'); // 延迟预载入
        $count = $article->getCount($where, $whereAssoc);
        // 补充完整文章的作者详情
        $config = new SystemConfig();
        $author = $config->getDetail(['group'=>'author']);
        foreach ($list as $key => $row){
            $list[$key]['user'] = $author;
        }

        return json(['total_count'=>$count, 'items'=>$list]);
    }

    public function read($id){
        //获取详情
        $article = new ArticleModel();
        $config = new SystemConfig();
        $detail = $article->getDetailById($id);
        $detail['user'] = $config->getDetail(['group'=>'author']);

        return json($detail);
    }

}